<template>
  <div class="froms-box">
    <div class="heards-box">
      <div>
        <t-tabs v-model="fromType" size="medium">
          <t-tab-panel
            size="medium"
            v-for="item in datas.tabs"
            :key="item.value"
            :value="item.value"
            :label="item.title"
          >
          </t-tab-panel>
        </t-tabs>
      </div>
    </div>
    <t-form
      labelAlign="right"
      ref="form"
      labelWidth="120px"
      :data="formData"
      :rules="rules"
      @submit="onSubmit"
      v-show="fromType == 1"
    >
      <t-card title="展品基本信息" class="dashboard-detail-card">
        <template #actions>
          <t-button theme="default" variant="outline" @click="blankRoute">返回</t-button>
        </template>
        <t-row :gutter="16">
          <t-col :span="12">
            <t-form-item label="展品名称" name="name">
              <t-input v-model="formData.name" placeholder="请输入展品名称"></t-input>
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="展品级别" name="levelId">
              <t-radio-group v-model="formData.levelId">
                <t-radio :value="item.id" v-for="item in datas.select1" :key="item.id">{{ item.text }}</t-radio>
              </t-radio-group>
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="开放状态" name="openStatus">
              <t-select v-model="formData.openStatus" :disabled="formData.id ? true : false">
                <t-option :key="1" label="公开" :value="1" />
                <t-option :key="2" label="私有" :value="2" />
              </t-select>
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="展品类型" name="typeId">
              <t-select v-model="formData.typeId">
                <t-option v-for="item in datas.select3" :key="item.id" :label="item.text" :value="item.id" />
              </t-select>
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="展品来源" name="sourceId">
              <t-select v-model="formData.sourceId">
                <t-option v-for="item in datas.select2" :key="item.id" :label="item.text" :value="item.id" />
              </t-select>
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="展品年代" name="ageId">
              <t-cascader
                v-model="formData.ageId"
                :options="datas.select4"
                valueType="full"
                :keys="{
                  value: 'id',
                  children: 'children',
                  label: 'text',
                }"
                clearable
                @change="onChange"
              />
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="具体年代" name="concreteTimes">
              <t-input v-model="formData.concreteTimes" placeholder="如：公元前475年"></t-input>
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="展品尺寸" name="gender">
              <t-input v-model="formData.size" placeholder="请输入展品尺寸"></t-input>
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="展品质地" name="texture">
              <t-input v-model="formData.texture" placeholder="请输入展品质地，如：宝石"></t-input>
            </t-form-item>
          </t-col>
          <t-col :span="12">
            <t-form-item label="3D链接" name="externalUrl">
              <t-input v-model="formData.externalUrl" placeholder="请输入3D链接"></t-input>
            </t-form-item>
          </t-col>
          <t-col :span="12">
            <t-form-item label="展品描述" name="gender">
              <DydEditor
                v-if="editLock"
                v-model="formData.Description"
                :Descriptions="formData.Description"
              ></DydEditor>
            </t-form-item>
          </t-col>
        </t-row>
      </t-card>
      <t-card title="展品图片上传" class="dashboard-detail-card">
        <t-row :gutter="16">
          <t-col :span="12">
            <t-form-item label="展品主图" name="coverUrl">
              <div>
                <t-upload
                  ref="uploadRef1"
                  v-model="filelist1"
                  accept="image/*"
                  :before-upload="beforeUpload"
                  :upload-all-files-in-one-request="uploadAllFilesInOneRequest"
                >
                  <div class="upload-boxs">
                    <img
                      v-if="!formData.coverUrl"
                      class="upload-boxs-item"
                      src="../../../assets/user/uer3.png"
                      alt=""
                    />

                    <img
                      class="upload-boxs-item t-image t-image--fit-contain t-image--position-center"
                      :src="$filters.getLinkUrl(formData.coverUrl, '?imageView2/2/w/120/h/120/format/webp')"
                      alt=""
                      v-else
                    />
                  </div>
                </t-upload>
              </div>
            </t-form-item>
          </t-col>
          <t-col :span="12">
            <t-form-item label="展品其他图片" name="images">
              <div>
                <t-upload
                  ref="uploadRef1"
                  v-model="filelist1"
                  :max="10"
                  multiple
                  accept="image/*"
                  :auto-upload="true"
                  :before-upload="beforeUpload1"
                  :upload-all-files-in-one-request="uploadAllFilesInOneRequest"
                >
                  <div class="upload-card-top">
                    <img src="../../../assets/img/upload.png" alt="" />
                    <span>支持批量上传，支持2M以内JPG、PNG图片</span>
                  </div>
                </t-upload>

                <t-base-table row-key="index" :data="formData.images" :columns="columns">
                  <template #data="{ row }">
                    <img
                      :src="$filters.getLinkUrl(row.data, webUrls)"
                      alt=""
                      class="img-box t-image t-image--fit-contain t-image--position-center"
                    />
                  </template>

                  <template #size="{ row }">
                    <span>{{ (row.size / 1000).toFixed(1) }}k</span>
                  </template>
                  <template #type="{ row, rowIndex }">
                    <div class="hw-box-style-flex">
                      <t-popup :overlay-style="{ width: '160px' }" destroy-on-close trigger="click" placement="bottom">
                        <template #content>
                          <div class="pop-box">
                            <div
                              class="pop-item hw-click-cursor"
                              @click="setcolStatus(item.value, rowIndex)"
                              v-for="(item, index) in datas.select5"
                              :key="index"
                            >
                              {{ item.text }}
                            </div>
                          </div>
                        </template>
                        <span class="hw-click-cursor select-boxs" :class="{ 'select-boxs-null': row.type !== 0 }">
                          <span v-if="row.type == 1">正视图</span>
                          <span v-else-if="row.type == 2">俯视图</span>
                          <span v-else-if="row.type == 3">侧视图</span>
                          <span v-else-if="row.type == 4">全景图</span>
                          <span v-else-if="row.type == 5">局部图</span>
                          <span v-else-if="row.type == 6">底部图</span>
                          <span v-else>未设置</span>
                          <t-icon name="chevron-down" size="16" color="#d2ad77"></t-icon>
                        </span>
                      </t-popup>
                    </div>
                  </template>
                  <template #status>
                    <t-icon name="check-circle-filled" size="14" color="rgba(0, 168, 112, 1)"></t-icon>
                    <span style="margin-left: 8px">上传成功</span>
                  </template>

                  <template #operation="{ row, rowIndex }">
                    <div class="operation-box">
                      <span class="hw-click-cursor" @click="look(row.data)">查看</span>
                      <span class="hw-click-cursor" @click="remove(rowIndex)">删除</span>
                    </div>
                  </template>
                </t-base-table>
              </div>
            </t-form-item>
          </t-col>
        </t-row>
      </t-card>
    </t-form>
    <div v-show="fromType == 2" class="pages-box">
      <internal-page>
        <template v-slot:left>
          <project-left @chageTab="chageTab"></project-left>
        </template>
        <template v-slot:right>
          <div class="right-box">
            <t-upload
              v-if="checked !== 1"
              ref="uploadRef1"
              v-model="formData.filelist2"
              :allowUploadDuplicateFile="true"
              :action="url"
              theme="custom"
              :headers="heards"
              accept="image/*"
              :auto-upload="true"
              :upload-all-files-in-one-request="uploadAllFilesInOneRequest"
              @fail="handleFail"
              @success="onSuccess3"
            >
              <div class="upload-card-top">
                <button class="hw-btn-style">{{ buttonTextList[checked].title }}</button>
                <span>{{ buttonTextList[checked].text }}</span>
              </div>
            </t-upload>
            <div class="upload-card-top" v-else>
              <button class="hw-btn-style" @click="addEdit">{{ buttonTextList[checked].title }}</button>
              <span>{{ buttonTextList[checked].text }}</span>
            </div>
            <t-base-table style="margin-top: 20px" row-key="index" :data="[]" :columns="pagescolumns"></t-base-table>
          </div>
        </template>
      </internal-page>
    </div>
    <t-image-viewer v-model:visible="lookVisible" :images="[lookImg]"> </t-image-viewer>

    <comment v-if="fromType == 3" :showpieceId="formData.id" />
    <itemModel v-if="visible" :visible="visible" @close="close" @submit="submit"></itemModel>
    <div class="btn-boxs" v-if="fromType == 1">
      <t-button @click="blankRoute" variant="outline">返回</t-button>
      <t-button :loading="loading" @click="save">保存</t-button>

      <!-- <button class="hw-btn-style" style="margin-left: 12px">保存</button> -->
    </div>
  </div>
</template>

<script setup lang="ts">
// @ts-nocheck
import { upLoadFn } from '@/utils/request/upload';
import comment from './comment.vue';
import { exhibitDirection, exhibitSave, exhibitInfo } from '@/api/exhibit/exhibit';
import { treeList } from '@/api/user/user';
import { useRouter, useRoute } from 'vue-router';
import itemModel from './addEdit.vue';
import projectLeft from './projectLeft.vue';
import internalPage from '@/components/Internalpage/index.vue';
import { url, heards, urls } from '@/utils/request/upload';
import { ref, reactive, computed, nextTick } from 'vue';
import { MessagePlugin } from 'tdesign-vue-next';
import DydEditor from '@/components/RichText/Editor.vue';
import { tabList2, tabList1, tabdatas, columns1, buttonText, pagescolumnsList } from '../data';
import { split } from 'lodash';
import { number } from 'echarts/core';
const checked = ref<number>(0);
const chageTab = (e: number): void => {
  checked.value = e;
};
const editLock = ref(false);
const lookImg = ref('');
const lookVisible = ref(false);
const webUrls: string = '?imageView2/2/w/60/h/60/format/webp';
const visible = ref(false);
const pdChild = ref(false);
const buttonTextList = buttonText;
const form = ref(null);
const fromType = ref(1);
const filelist1 = ref([]);
const filelist2 = ref([]);
const formData = reactive({
  id: 0,
  name: null, //名称
  coverUrl: '', //封面
  ageId: [], //年代
  ageIds: null,
  levelId: null, //级别
  typeId: null, //类型
  sourceId: null, //来源
  concreteTimes: null, //具体年代
  size: '', //尺寸
  texture: null, //质地
  openStatus: 0, //开放状态
  images: [],
  Description: '',
  externalUrl: null,
});
const loading = ref(false);
const columns = columns1;
const uploadAllFilesInOneRequest = ref(false);
const router = useRouter();
const route = useRoute();
const datas = reactive({
  tabs: tabList1,
  select1: [], //展品级别
  select2: [], //展品来源
  select3: [], //展品类型
  select4: [],
  select5: [], //方向
});
const init = async () => {
  let { data } = await exhibitInfo(Number(route.query.id));
  formData.name = data.name;
  formData.coverUrl = data.coverUrl;
  formData.ageId = data.ageId; //data.ageId;
  let arrns = data.ageIds ? data.ageIds.split(',') : null;
  let arrns1 = [];
  if (arrns) {
    arrns.forEach((element) => {
      arrns1.push(Number(element));
    });
  }

  //formData.ageIds = data.ageIds ? data.ageIds.split(',') : null; //data.ageId;
  formData.ageId = arrns1; //data.ageId;
  formData.levelId = data.levelId;
  formData.typeId = data.typeId;
  formData.sourceId = data.sourceId;
  formData.concreteTimes = data.concreteTimes;
  formData.size = data.size;
  formData.texture = data.texture;
  formData.openStatus = data.openStatus;
  formData.images = data.images;
  formData.Description = data.description;
  formData.externalUrl = data.externalUrl;
  formData.id = Number(route.query.id);
  nextTick(() => {
    editLock.value = true;
  });
};
// console.log(route.query.id);
if (route.query.type) {
  formData.openStatus = Number(route.query.type);
}

if (route.query.id) {
  datas.tabs = tabList2;
  init();
} else {
  editLock.value = true;
}

const pagescolumns = computed(() => {
  let num: any = checked.value;
  const columns = pagescolumnsList[num];
  return columns;
});

const onSubmit = async ({ validateResult, firstError, e }) => {
  e.preventDefault();
  if (validateResult === true) {
    formData.ageIds = '';
    let arrays = formData.ageId ? formData.ageId : [];
    arrays.forEach((element) => {
      formData.ageIds = formData.ageIds + element + ',';
    });
    formData.ageIds = formData.ageIds ? formData.ageIds.slice(0, formData.ageIds.length - 1) : '';
    formData.ageId = formData.ageId ? formData.ageId[formData.ageId.length - 1] : 0;
    loading.value = true;
    formData.ageId = formData.ageId ?? 0;
    formData.levelId = formData.levelId ?? 0;
    formData.typeId = formData.typeId ?? 0;
    formData.sourceId = formData.sourceId ?? 0;
    try {
      let { statusCode } = await exhibitSave(formData);
      if (statusCode == 200) {
        if (formData.id) {
          MessagePlugin.success('修改成功');
        } else {
          MessagePlugin.success('创建成功');
        }

        router.push('/Exhibits/ExhibitLibrary');
      }
      loading.value = false;
    } catch {
      loading.value = false;
    }
  } else {
    MessagePlugin.warning(firstError);
  }
};
const blankRoute = () => {
  // '返回展品库'
  router.go(-1);
};
const rules = {
  name: [{ required: true, message: '展品名称必填', type: 'error' }],
  coverUrl: [{ required: true, message: '请添加封面', type: 'error' }],
  ageId: [{ required: true, message: '请选择年代', type: 'error' }],
  levelId: [{ required: true, message: '请选择级别', type: 'error' }],
  typeId: [{ required: true, message: '请选择类型', type: 'error' }],
  images: [
    // { validator: (val) => val.length >= 1, message: '至少上传1张展品正面图片' },
    // { required: true, message: '请添加展品其他图片', type: 'error' },
  ],
  //   openStatus: [{ required: true, message: '请选择开放状态', type: 'error' }],
};
const getSelectList = async () => {
  let res = await treeList(371994471206981); //级别
  let res1 = await treeList(371996102197317); //来源
  let res2 = await treeList(371999507447877); //类型
  let res3 = await treeList(372051821408325); //年代
  let res4 = await exhibitDirection(); //方向
  datas.select1 = res.data;
  datas.select2 = res1.data;
  datas.select3 = res2.data;
  datas.select4 = res3.data;
  datas.select5 = res4.data;
};
const look = (e: string) => {
  //查看图片
  lookImg.value = urls + e;
  lookVisible.value = true;
};
const onSuccess2 = (e) => {
  // console.log(formData.coverUrl);
};
const beforeUpload = (file: any) => {
  //回调钩子
  if (file.type.indexOf('image/') == -1) {
    MessagePlugin.error('文件类型错误');
    return;
  }
  upLoadFn(file).then((res) => {
    // console.log(res);
    if (res) {
      formData.coverUrl = res;
    } else {
      MessagePlugin.error('创建成功');
    }
  });
};
const beforeUpload1 = (file: any) => {
  //回调钩子
  // console.log(file);
  if (file.type.indexOf('image/') == -1) {
    MessagePlugin.error('文件类型错误');
    return;
  }
  if (file.size / 1048576 > 2) {
    MessagePlugin.error('上传大小超出2M限制');
    return;
  }
  upLoadFn(file).then((res) => {
    // console.log(res);
    if (res) {
      let obj = {
        data: res,
        type: 0,
        size: file.size,
        status: '上传完成',
        operation: null,
      };
      formData.images.push(obj);
    } else {
      MessagePlugin.error('上传失败');
    }
  });
};
getSelectList();
const handleFail = (e) => {};

const onSuccess3 = (e) => {};
const submit = () => {
  visible.value = false;
};
const onChange = (e) => {
  console.log(e);
};
const close = (e: boolean) => {
  visible.value = false;
};
const addEdit = () => {
  visible.value = true;
};
const setImgType = (e: any) => {
  console.log(e);
};
const setcolStatus = (index, rowIndex) => {
  formData.images[rowIndex].type = index;
};
const remove = (e: number) => {
  formData.images.splice(e, 1);
};
const save = () => {
  form.value.submit();
};
</script>

<style lang="less" scoped>
.froms-box {
  width: 100%;
  :deep(.t-tabs__nav-item-wrapper) {
    height: 64px;
  }
}
.heards-box {
  width: 100%;
  height: 66px;
  padding: 0 20px;
  background: #fefefe;
  border-radius: @radius-hw-box1;
  border: 1px solid #d2ad77;
  div {
    height: 64px;
  }
}
.t-button--variant-outline {
  border-color: var(--td-border-level-2-color);
}
.t-button__text {
  color: #fff;
}
.t-tabs {
  height: 100%;
}
.dashboard-detail-card {
  border-color: @color-text-color;
  margin-top: 20px;
}
.t-col {
  margin-top: 18px;
}
.upload-boxs {
  width: 120px;
  height: 120px;
  .upload-boxs-item {
    width: 120px;
    height: 120px;
    border-radius: 6px;
  }
}
.upload-card-top {
  display: flex;
  align-items: center;
  img {
    width: 112px;
    height: 32px;
  }
  span {
    margin-left: 12px;
    font-size: 12px;
    font-weight: 400;
    color: rgba(0, 0, 0, 0.4);
    line-height: 20px;
  }
}
.pages-box {
  margin-top: 20px;
}
.right-box {
  padding: 24px;
  border-radius: @radius-hw-box1;
  border: 1px solid #d2ad77;
  background: #fff;
  height: 100%;
}
.btn-boxs {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 20px;
}
.t-dialog {
  min-width: 600px !important;
}
.operation-box {
  display: flex;
  align-items: center;

  width: 100%;
  span {
    font-size: 16px;
    font-weight: 400;
    color: rgba(210, 173, 119, 0.9);
    line-height: 22px;
    margin-right: 12px;
  }
}
.pop-box {
  display: flex;
  flex-direction: column;
  width: 100%;
  padding: 4px;
}
.pop-item {
  display: flex;
  width: 100%;
  padding: 7px 20px;
  font-size: 13px;
}
.pop-item:hover {
  background: #f0e9e1;
  color: rgba(210, 173, 119, 0.9);
}
.img-box {
  width: 60px;
  height: 60px;
}
.select-boxs {
  display: flex;
  align-items: center;
  justify-content: space-between;

  border-radius: 4px;
  span {
    margin-right: 4px;
    color: #d2ad77;
  }
}
.select-boxs-null {
}
:deep(.t-table__content) {
  border-bottom: 1px solid #e7e7e7;
  // border-bottom: none;
}
.t-row {
  margin: 0;
}
:deep(.t-card__body) {
  padding: 32px 112px;
}
:deep(.t-table) {
  border: 1px solid #e7e7e7;
  border-bottom: none;
}
:deep(.t-image) {
  // background: #999;

  background: #d8d8d8;
}
</style>
